package com.aabte.commons.encrypt.rsa;

import com.aabte.commons.encrypt.EncryptException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/3/28
 */
public class RSAPublicKeyEncryptor extends AbstractEncryptorRSA<PublicKey> {

  @Override
  public PublicKey key() {
    KeySpec keySpec = new X509EncodedKeySpec(getPublicKeyBytes());
    KeyFactory keyFactory;
    try {
      keyFactory = KeyFactory.getInstance(getAlgorithm());
      return keyFactory.generatePublic(keySpec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
      throw new EncryptException(e);
    }
  }

  @Override
  public byte[] encrypt(byte[] plainText) {
    KeySpec keySpec = new X509EncodedKeySpec(getPublicKeyBytes());
    KeyFactory keyFactory;
    try {
      keyFactory = KeyFactory.getInstance(getAlgorithm());
      PublicKey publicKey = keyFactory.generatePublic(keySpec);
      return segmentEncrypt(plainText, publicKey);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
      throw new EncryptException(e);
    }
  }

  @Override
  public byte[] decrypt(byte[] cipherText) {
    try {
      KeySpec keySpec = new X509EncodedKeySpec(getPublicKeyBytes());
      KeyFactory keyFactory = KeyFactory.getInstance(getAlgorithm());
      PublicKey publicKey = keyFactory.generatePublic(keySpec);
      return segmentDecrypt(cipherText, publicKey);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
      throw new EncryptException(e);
    }
  }
}
